package services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Item;
import model.Member;
import model.Photo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import utils.WebUtils;
import core.Lookup;
import core.ManagerLocal;
import core.MemberManagerLocal;

public class ListItemPhoto extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		process(req,resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		String memberCellphone = WebUtils.safeGetParameterString(req, "memberCellphone");
		String memberEmail = WebUtils.safeGetParameterString(req, "memberEmail");
		String memberPassword = WebUtils.safeGetParameterString(req, "memberPassword");
		
		Integer idItem = WebUtils.safeGetParameterInteger(req, "idItem");
		
		if(idItem == null){
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "idItem parameter is required");
			return;
		}
		
		ManagerLocal manager = Lookup.lookupManager();
		MemberManagerLocal memberManager = Lookup.lookupMemberManager();
		
		Member member = memberManager.loginMember(memberCellphone, memberEmail, memberPassword);
		
		if(member == null || !member.isSuperAdmin()){
			resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "not authorized");
			return;	
		}
		
		Item item = manager.get(Item.class, idItem);
		
		if(item == null){
			resp.sendError(HttpServletResponse.SC_NOT_FOUND, "item not found");
			return;
		}		
		
		List<Photo> photos = manager.listPhotos(idItem);
		
		try {
			JSONObject jsonObj = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			
			for (Photo photo : photos) {
				jsonArray.put(new JSONObject(photo.toString()));
			}
			
			jsonObj.put("photos", jsonArray);
			jsonObj.put("success", true);
			String outputString = jsonObj.toString();
			
			PrintWriter writer = resp.getWriter();
			resp.setContentType("text/html;charset=UTF-8");
			writer.print(outputString);
			writer.close();
		
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}		
	}
}
